package com.ccteam.fluidmusic.ui.auth

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import cn.hutool.core.lang.Validator
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.databinding.FragmentForgetPasswordBinding
import com.ccteam.fluidmusic.utils.EventObserver
import com.ccteam.fluidmusic.utils.VerifyCodeCountDownTimer
import com.ccteam.fluidmusic.view.bean.LoadMessage
import com.ccteam.fluidmusic.widget.SNACKBAR_ALL_BOTTOM_BAR
import com.ccteam.fluidmusic.widget.SNACKBAR_BOTTOM
import com.ccteam.fluidmusic.widget.snackbar
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * @author Xiaoc
 * @since 2021/4/16
 */
@AndroidEntryPoint
class ForgetPasswordFragment: Fragment() {

    private var _binding: FragmentForgetPasswordBinding? = null
    private val binding get() = _binding!!

    private val forgetPasswordViewModel by viewModels<ForgetPasswordViewModel>()

    private val verifyCodeCountDownTimer = VerifyCodeCountDownTimer()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentForgetPasswordBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        binding.toolbarForgetPassword.setNavigationOnClickListener {
            findNavController().navigateUp()
        }

        viewLifecycleOwner.lifecycleScope.launch {
            verifyCodeCountDownTimer.countDown.collectLatest {
                if(it is VerifyCodeCountDownTimer.Status.Timing){
                    updateTiming(it.currentCountDownNum)
                } else {
                    updateNotTiming()
                }
            }
        }

        forgetPasswordViewModel.loadMessage.observe(viewLifecycleOwner,EventObserver{
            binding.btnForgetPassword.setLoading(it is LoadMessage.Loading)
            when (it) {
                is LoadMessage.Error -> {
                    view.snackbar(it.errorMessage.description.toString(), SNACKBAR_BOTTOM).show()
                }
                is LoadMessage.Success -> {
                    view.snackbar(R.string.description_success_forget_password, SNACKBAR_ALL_BOTTOM_BAR).show()
                    findNavController().navigateUp()
                }
                else -> {}
            }
        })

        forgetPasswordViewModel.enableCountDown.observe(viewLifecycleOwner,EventObserver{
            if(it){
                verifyCodeCountDownTimer.start()
            }
        })

        forgetPasswordViewModel.enableForgetPasswordButton.observe(viewLifecycleOwner, {
            binding.btnForgetPassword.isEnabled = it
        })

        forgetPasswordViewModel.enableVerifyCodeButton.observe(viewLifecycleOwner, {
            binding.btnVerify.isEnabled = it && verifyCodeCountDownTimer.countDown.value !is VerifyCodeCountDownTimer.Status.Timing
        })

        binding.editPhone.addOnEditTextAttachedListener {  inputLayout ->
            inputLayout.editText?.doOnTextChanged { text, _, _, _ ->
                forgetPasswordViewModel.setPhoneSuccess(Validator.isMobile(text.toString()))
            }
        }

        binding.editPassword.addOnEditTextAttachedListener { inputLayout ->
            inputLayout.editText?.doOnTextChanged { text, _, _, _ ->
                if(checkPasswordRegex(text.toString())
                    && text.toString().length in 8..16){
                        forgetPasswordViewModel.setPasswordSuccess(true)
                    inputLayout.error = null
                } else {
                    forgetPasswordViewModel.setPasswordSuccess(false)
                    inputLayout.error = getString(R.string.description_error_name_password)
                }
            }
        }

        binding.editPasswordConfirm.addOnEditTextAttachedListener { inputLayout ->
            inputLayout.editText?.doOnTextChanged {  text, _, _, _ ->
                if(text.toString() != binding.editPassword.editText?.text.toString()){
                    forgetPasswordViewModel.setConfirmPasswordSuccess(false)
                    inputLayout.error = getString(R.string.description_error_name_password_confirm)
                } else {
                    forgetPasswordViewModel.setConfirmPasswordSuccess(true)
                    inputLayout.error = null
                }
            }
        }

        binding.editVerifyCode.addOnEditTextAttachedListener { inputLayout ->
            inputLayout.editText?.doOnTextChanged { text, _,_,_ ->
                forgetPasswordViewModel.setVerifyCodeSuccess(text.toString().isNotEmpty())
            }
        }

        binding.btnForgetPassword.setProgressButtonOnClickListener{
            forgetPasswordViewModel.forgetPassword(
                binding.editPhone.editText?.text.toString(),
                binding.editPassword.editText?.text.toString(),
                binding.editVerifyCode.editText?.text.toString()
            )
        }

        binding.btnVerify.setProgressButtonOnClickListener{
            forgetPasswordViewModel.getVerification(
                binding.editPhone.editText?.text.toString()
            )
        }

    }

    /**
     * 判断密码是否符合条件
     * 必须满足 数字，字母，特殊字符两种类型及以上才满足
     * @return true 通过条件 false 不通过
     */
    private fun checkPasswordRegex(password: String): Boolean{
        var i = 0
        if(password.matches(RegisterFragment.REG_NUMBER)){
            i++
        }
        if(password.matches(RegisterFragment.REG_UPPERCASE)){
            i++
        }
        if(password.matches(RegisterFragment.REG_UPPERCASE) || password.matches(RegisterFragment.REG_LOWERCASE)){
            i++
        }
        if(password.matches(RegisterFragment.REG_SYMBOL)){
            i++
        }
        return i >= 2
    }

    private fun updateTiming(countDownNum: Int){
        binding.btnVerify.isEnabled = false
        binding.btnVerify.text = countDownNum.toString()
    }

    private fun updateNotTiming(){
        binding.btnVerify.isEnabled = true && forgetPasswordViewModel.enableVerifyCodeButton.value == true
        binding.btnVerify.text = getString(R.string.description_get_verification)
    }

    override fun onDestroyView() {
        super.onDestroyView()

        _binding = null
    }
}